package cn.chinaunicom.admin.config;

import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Base64Utils;

import cn.chinaunicom.fast.common.constant.AuthConstant;
import cn.chinaunicom.fast.common.utils.FebsUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;

/**
 * @ProjectName: cloud
 * @Package: cn.chinaunicom.smart.community.feigns.config
 * @ClassName: FeignConfiguration
 * @Description: feignClient配置
 * @Author: wangjc
 * @CreateDate: 2020/4/8 0008 15:29
 * @UpdateUser: 更新者
 * @UpdateDate: 2020/4/8 0008 15:29
 * @UpdateRemark: 更新内容
 * @Version: 1.0
 */
@Slf4j
public class FeignConfiguration implements RequestInterceptor {

    private final static String IS_TURE = "true";

    @Override
    public void apply(RequestTemplate template) {
        HttpServletRequest request = FebsUtil.getHttpServletRequest();
        // 1.设置客户端token
        String gatewayToken = Base64Utils.encodeToString((AuthConstant.X_CLIENT_TOKEN + "$" + AuthConstant.CLIENT_TOKEN_SECURE).getBytes());
        template.header(AuthConstant.X_CLIENT_TOKEN, gatewayToken);

        if(Objects.isNull(request)){
            // 通过消息队列调用的feignClient, 没有会话
            // 2.设置feign客户端标识
            template.header(AuthConstant.X_CLIENT_FEIGN, IS_TURE);
        } else {
            // 通过请求访问接口方式调动的feignClient, 有会话
            // 3.获取并设置用户登录信息
            String userInfoString = request.getHeader(AuthConstant.X_CLIENT_TOKEN_USER);
            if(StringUtils.isBlank(userInfoString)){
                template.header(AuthConstant.X_CLIENT_FEIGN, IS_TURE);
            } else {
                template.header(AuthConstant.X_CLIENT_TOKEN_USER, userInfoString);
            }
        }

    }
}
